import { get } from 'lodash'
// 找出树状数组内选中和半选的节点id
export const useCheckedFormat = (tree: any, selectedIds: any) => {
    const halfChecked: any = [];
    // 递归调用检查子节点的选中状态
    const checkAllChildrenSelected = (node: any, selectedIds: any) => {
        for (const child of node?.children) {
            if (!checkAllChildrenSelected(child, selectedIds)) {
                return false; // 如果子节点有未被选中的，则返回 false
            }
        }
        return selectedIds.includes(node.id);
    };
    const traverse = (node: any) => {
        node?.forEach((item: any) => {
            if (selectedIds.includes(item.id) && !checkAllChildrenSelected(item, selectedIds)) {
                halfChecked.push(item.id)
            }
            traverse(item.children)
        })
    }
    traverse(tree)
    return {
        halfChecked,
        checked: selectedIds?.filter((item: any) => !halfChecked.includes(item))
    };
}
// 根据路由名称查询当前菜单和父级菜单
export const useMenuTreeFind = (tree: any, url: any) => {
    let result: any = [];
    const traverse = (node: any, ancestors: any = []) => {
        if (node.url === url) {
            result = [...ancestors, node];
            return;
        }
        if (node.children && node.children.length > 0) {
            for (const child of node.children) {
                traverse(child, [...ancestors, node]);
            }
        }
    }
    for (const node of tree) {
        traverse(node);
        if (result.length > 0) {
            break;
        }
    }
    return result;
}
// 获取树状数组所有id
export const useTreeAllId = (tree: any): any => {
    let ids = [];
    for (let node of tree) {
        ids.push(node.id); // 将当前节点的ID添加到数组中
        ids = ids.concat(useTreeAllId(node.children)); // 递归获取子节点的ID
    }
    return ids;
}
export const useTreeToList = (arr: any[]): any => {
    let result = []
    for (let item of arr) {
        var res = JSON.parse(JSON.stringify(item))
        delete res['children']
        result.push(res)
        if (item.children instanceof Array && item.children.length > 0) {
            result = result.concat(useTreeToList(item.children))
        }
    }
    return result
}
export const useListToTree = (list: any) => {
    const map = new Map();
    const tree: any = [];

    // 先将所有项存入map，并准备好children数组
    list.forEach((item: any) => {
        map.set(item.id, { ...item, children: [] });
    });

    // 然后将每个项添加到其父项的children数组中
    list.forEach((item: any) => {
        const parent = map.get(item.pid);
        if (parent) {
            parent.children!.push(map.get(item.id)!);
        } else {
            // 如果没有父项，则为根节点
            tree.push(map.get(item.id)!);
        }
    });

    return tree;
}
const extractMenu = (node: any, level: any, result: any) => {
    let obj = cloneDeep(node)
    delete obj.children
    obj.level = level
    result.push(obj);
    if (node?.children?.length) {
        for (const childNode of node.children) {
            extractMenu(childNode, level + 1, result);
        }
    }
}
// 获取功能菜单
export const useModuleMenu = (treeData: any) => {
    const result: any = [];
    for (const node of treeData) {
        extractMenu(node, 1, result);
    }
    return result.filter((menu: any) => [1, 3].includes(menu.level)).map((item: any) => {
        delete item.level
        return item
    });
}

export const useGenerateRandomLatLonWithinDistance = (center: any, maxDistance: any) => {
    const radiusEarth = 6371000; // 地球半径，单位：米
    const degreesToRadians = Math.PI / 180.0;
    const radiansToDegrees = 180.0 / Math.PI;

    // 将距离转换为经纬度度数
    const distanceInDegrees = (maxDistance / radiusEarth) * radiansToDegrees;

    // 生成随机纬度
    const deltaLat = distanceInDegrees * (Math.random() * 2 - 1);
    const randomLat = center[1] + deltaLat;

    // 生成随机经度，需要考虑纬度影响
    const deltaLon = distanceInDegrees / Math.cos(center[1] * degreesToRadians) * (Math.random() * 2 - 1);
    const randomLon = center[0] + deltaLon;

    return [randomLon, randomLat];
}


export const useUniqueByFields = (arr:any, field1:any, field2:any) => {
    const unique:any = [];
    arr?.forEach((item:any) => {
      const found = unique.some((el:any) => get(el,field1) === get(item,field1) && get(el,field2) === get(item,field2));
      if (!found) {
        unique.push(item);
      }
    });
    return unique;
  }
//   根据经纬度对侦察记录去重
  export const useUniqueUavLocations = (data: any) => {
    const seenCoordinates = new Set<string>();
    const uniqueData: any[] = [];
  
    for (const item of data) {
      const coordinateKey = `${item.uavLocation.lat},${item.uavLocation.lon}`;
      if (!seenCoordinates.has(coordinateKey)) {
        seenCoordinates.add(coordinateKey);
        uniqueData.push(item);
      }
    }
  
    return uniqueData;
  }
//   数组根据指定数量分割
  export const useChunkArray = (array:any, chunkSize=20) => {
    let result = [];
  
    for (let i = 0; i < array.length; i += chunkSize) {
      let chunk = array.slice(i, i + chunkSize);
      result.push(chunk);
    }
  
    return result;
  }